﻿using GRPCClass;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SdtpsBase
{
    public class Util
    {
        public delegate void ExecuteEventHandler(ITaskWorker SoureTaskWorker ,TaskRequest sender);
        /// <summary>
        /// 把字符转换为整数
        /// </summary>
        /// <param name="str1"></param>
        /// <returns></returns>
        public static int StrToInt(string str1)
        {
            unchecked //用checked抛出了溢出异常，而unchecked只是将溢出的位丢弃而得到剩下的32位组成的十进制整数值
            {
                int g;
                if (string.IsNullOrEmpty(str1) == true)
                { return 0; }
                else if (string.Compare(str1, "false", true) == 0)
                { return 0; }
                else if (string.Compare(str1, "true", true) == 0)
                { return 1; }
                else if (str1 == ".")
                { return 0; }
                else if (string.Compare(str1, "-", true) == 0)
                { return 0; }
                System.Text.RegularExpressions.Regex reg
                    = new System.Text.RegularExpressions.Regex(@"^(-?[0-9]*[.]*[0-9]{0,4})$");
                if (reg.IsMatch(str1))
                {
                    if (str1.IndexOf(".") >= 0)
                    { str1 = str1.Substring(0, str1.IndexOf(".")); }
                    if (string.IsNullOrEmpty(str1) == true)
                    { str1 = "0"; }
                    try
                    {
                        g = Convert.ToInt32(str1);
                    }
                    catch (System.FormatException cw)
                    {
                        System.Diagnostics.Debug.Print(cw.Message);
                        return 0;
                    }
                    return g;
                }
                else
                { return 0; }
            }
        }
        private static object lockObject = new object();
        /// <summary>
        /// 向指定文件写入日志内容
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="text">写入内容</param>
        /// <param name="fileMaxSize">文件最大的大小，如果超过此值将备份文件并重新写入，0无限制。</param>
        public static void WriteText(string fileName, string text, int fileMaxSize)
        {
            lock (lockObject)
            {
                if (System.IO.File.Exists(fileName))
                {
                    //如果文件过大，则把文件改名并重新写文件。
                    System.IO.FileInfo fi = new System.IO.FileInfo(fileName);
                    if (fileMaxSize > 0 && fi.Length > fileMaxSize)
                    {
                        string name = System.IO.Path.GetFileNameWithoutExtension(fileName) + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss");
                        string backupName = System.IO.Path.Combine(fi.DirectoryName, name);
                        if (System.IO.File.Exists(backupName + fi.Extension))
                        {
                            //查找以destFileName开始的所有文件名，试图加上最大序号来命名新的文件名
                            int maxNum = 0;
                            int tmp;
                            string strNum;
                            foreach (string file in System.IO.Directory.GetFiles(fi.DirectoryName, String.Format("{0}*{1}", name, fi.Extension), System.IO.SearchOption.TopDirectoryOnly))
                            {
                                tmp = 0;
                                strNum = System.IO.Path.GetFileNameWithoutExtension(file).Remove(0, name.Length);
                                if (strNum.Length > 0)
                                {
                                    strNum = strNum.Substring(1);
                                }
                                if (int.TryParse(strNum, out tmp) && tmp > maxNum)
                                {
                                    maxNum = tmp;
                                }
                            }
                            //再有复名的可能性很小，不再判断是否存在。
                            backupName = String.Format("{0}_{1}", backupName, (maxNum + 1));
                        }
                        fi.MoveTo(backupName + fi.Extension);
                    }
                }
                using (System.IO.TextWriter tw = new System.IO.StreamWriter(fileName, true))
                {
                    tw.WriteLine(text);
                }
            }
        }
    }
}
